using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Text.RegularExpressions;

using System.Threading;
using System.Globalization;

using System.Collections;
using CE.Database;
using CE.Configuration;
/// <summary>
/// Summary description for General
/// </summary>
/// 
namespace CE.Global
{
    public class General
    {
        public static string UserId = "UserId";
        public static string UserRole = "UserRole";
        public static string UserProfileAndContactComplete = "IsProfileContactComplete";

        public static string UserTypeId = "UserTypeId";
        public static string UserEmail = "UserEmail";
        public static string UserPhoneNo = "UserPhone";
        public static string UserName = "UserName";
        public static string UserICNumber = "UserICNumber";
        public static string RequestUrl = "RequestUrl";
        public static string StartTime = "StartTime";
        public static string Guest = "Guest";
        public static string LoginHistoryId = "LoginHistoryId";
        public static string LastLoginTime = "LastLoginTime";
        public static string SecurityCheckWord = "Salt";
        //Car Insurance Session
        public static string CarServiceName = "Car Insurance";
        public static string CarId = "CarId";
        public static string CarPolicyId = "CarPolicyId";
        public static string CarResultId = "CarResultId";
        public static string CarMoreDetailId = "CarMoreDetailId";
        public static string CarClaimHistoryId = "CarClaimHistoryId";
        public static string CvvId = "CvvId";
        public static string IsCarDetailChange = "IsCarDetailChange";

        //Home Loan
        public static string HFServiceName = "Home Loans";
        public static string HFId = "HFID";
        public static string HFPersonnelId = "HFPersonnelID";
        public static string HFResultId = "HFResultId";
        public static string HFPropertyId = "HFPropertyId";
        public static string HFUserName = "HFUserName";
        public static string HFPhoneNo = "HFPhoneNo";
        public static string HFEmail = "HFEmail";

        //Personal Loan
        public static string PLServiceName = "Personal Loans";
        public static string PLId = "PLID";
        public static string PLUserName = "PLUserName";
        public static string PLPhoneNo = "PLPhoneNo";
        public static string PLEmail = "PLEmail";
        public static string PLPersonnelId = "PLPersonnelID";
        public static string PLResultId = "PLResultId";

        public static string PLEmpId = "PLAREID";

        //Personal Accident
        public static string PAServiceName = "Personal Accident";
        public static string PAId = "PAID";
        public static string PAUserName = "PAUserName";
        public static string PAPhoneNo = "PAPhoneNo";
        public static string PAEmail = "PAEmail";
        public static string PAPersonnelId = "PAPersonnelID";
        public static string PAResultId = "PAResultId";
        public static string PAProposalId = "PAProposalId";

        //Travel Insurance
        public static string TAServiceName = "Travel Insurance";
        public static string TAId = "TAID";
        public static string TAUserName = "TAUserName";
        public static string TAPhoneNo = "TAPhoneNo";
        public static string TAEmail = "TAEmail";
        public static string TAPersonnelId = "TAPersonnelID";
        public static string TAResultId = "TAResultId";
        public static string TACustomerAge = "TACustomerAge";

        //Provider Session
        public static string ProviderCompanyId = "ProviderCompanyId";
        public static string ProviderProfileFirstTime = "IsProviderProfileFirstTime";

        //CreditCard Compare Request
        public static string CCServiceName = "Credit Cards";
        public static string CCARId = "CCARID";
        public static string CCRequestStatus = "CCRequestStatus";
        public static string CCId = "CCID";
        public static string CCRFullName = "CCRFullName";
        public static string CCRMobileNo = "CCRMobileNo";
        public static string CCREmail = "CCREmail";
        public static string CCPersonnelId = "CCPERSONNELID";


        //View Details ID
        public static string ViewedDetailsId = "ViwedDetailsId";

        //DownLoad Proposal
        public static string RefId = "RefId";
        public static string InsType = "InsType";
        public static string InsParam = "InsParam";
        //Feed Back Receiver
        public General()
        {
            //
            // TODO: Add constructor logic here
            //
        }
        public static DataTable GetComboItem(string keyName, bool status)
        {
            DataTable _dt = null;
            try
            {
                MyDatabase _db = new MyDatabase();

                string _keyValue = MyConfigurationManager.GetAppSettingValue(keyName);
                string[] _keyValueList = _keyValue.Split(',');

                string _sqlstatement = "SELECT " + _keyValueList[2] + ", " + _keyValueList[1] + " FROM " + _keyValueList[0];
                string _sqlwhere = "";

                if (status)
                {
                    _sqlwhere = " Where [Status] = 1 ";
                    _sqlstatement += _sqlwhere;
                }

                _sqlstatement += " Order By " + _keyValueList[1];
                _dt = _db.GetDataTable(_sqlstatement);
            }
            catch (Exception Ex)
            {
            }

            return _dt;
        }
        
        public static DataTable GetComboItem(string keyName, string OrderBy, bool status)
        {
            DataTable _dt = null;
            try
            {
                MyDatabase _db = new MyDatabase();

                string _keyValue = MyConfigurationManager.GetAppSettingValue(keyName);
                string[] _keyValueList = _keyValue.Split(',');

                string _sqlstatement = "SELECT " + _keyValueList[2] + ", " + _keyValueList[1] + " FROM " + _keyValueList[0];
                string _sqlwhere = "";

                if (status)
                {
                    _sqlwhere = " Where [Status] = 1 ";
                    _sqlstatement += _sqlwhere;
                }

                if (OrderBy != "")
                {
                    _sqlstatement += " Order by " + OrderBy;
                }

                _dt = _db.GetDataTable(_sqlstatement);
            }
            catch (Exception Ex)
            {
            }

            return _dt;
        }
        
        public static DataTable GetComboItem(string keyName, string whereKey, string whereId, bool status)
        {
            DataTable _dt = null;
            try
            {
                MyDatabase _db = new MyDatabase();

                string _keyValue = MyConfigurationManager.GetAppSettingValue(keyName);
                string[] _keyValueList = _keyValue.Split(',');

                string _sqlstatement = "SELECT " + _keyValueList[2] + ", " + _keyValueList[1] + " FROM " + _keyValueList[0];
                _sqlstatement += " WHERE " + whereKey + " = " + whereId;
                string _sqlwhere = "";

                if (status)
                {
                    _sqlwhere = " AND [Status] = 1;";
                    _sqlstatement += _sqlwhere;
                }

                _dt = _db.GetDataTable(_sqlstatement);
            }
            catch (Exception Ex)
            {
            }

            return _dt;
        }

        public static Int64 IsExistId(string tblName, string filterFieldName, Int64 filterValue, bool status)
        {
            MyDatabase _db = new MyDatabase();
            string _sql = "Select " + filterFieldName + " from " + tblName + " WHERE " + filterFieldName + " = @filterValue";

            //SqlParameter[] _sqlpara = new SqlParameter();

            //object _result = _db.ExecuteScalarSqlStatement(_sql, _sqlpara);

            return 1;
        }

        public static Hashtable GetDayList(int sMonth, int sYear)
        {
            int _daycount = 31;
            bool isLeapYear = DateTime.IsLeapYear(sYear);

            if (isLeapYear && sMonth == 2)
            {
                _daycount = 29;
            }
            else if (sMonth == 2)
            {
                _daycount = 28;
            }
            else if (sMonth == 4 || sMonth == 6 || sMonth == 9 || sMonth == 11)
            {
                _daycount = 30;
            }
            else
            {
                _daycount = 31;
            }
            Hashtable ht_day = new Hashtable(_daycount);
            for (int i = _daycount; i >= 1; i--)
            {
                ht_day.Add(i, i);
            }

            return ht_day;
        }

        public static Hashtable GetDOBYearList()
        {
            int _sYear = Convert.ToInt32(MyConfigurationManager.GetAppSettingValue("StartDOBYear"));
            int _eYear = Convert.ToInt32(MyConfigurationManager.GetAppSettingValue("EndDOBYear"));
            int _yCount = _eYear - _sYear;
            Hashtable ht_year = new Hashtable(_yCount);

            for (int i = _sYear; i <= _eYear; i++)
            {
                ht_year.Add(i, i);
            }

            return ht_year;
        }

        public static Hashtable GetMonthList(string format)
        {
            Hashtable ht_month = new Hashtable(12);
            DateTime dt = new DateTime(2009, 1, 1);
            for (int i = 1; i <= 12; i++)
            {
                string monthName = string.Format("{0:" + format + "}", dt.AddMonths(i - 1));
                ht_month.Add(i, monthName);
            }
            return ht_month;
        }

        public static string ClearScriptTag(string strSource)
        {
            String sourcestring = strSource;
            String matchpattern = @"<script[^>]*?.*?</script>";
            //String matchpattern = @"<script\s[^>]*?</script>";
            //String matchpattern = @"<script\s[^>]*>(?:(?!</script>).)*?\r\n(?:function blabla\(\)|blabla\(\);)(?:(?!</script>).)*?</script>";
            String replacementpattern = @"";
            String result = Regex.Replace(sourcestring, matchpattern, replacementpattern, RegexOptions.IgnoreCase);
            return result;
        }

        public static bool IsInteger(String strNumber)
        {
            Regex objNotNaturalPattern = new Regex("[^0-9]");
            Regex objNaturalPattern = new Regex("[0-9][0-9]*");

            return !objNotNaturalPattern.IsMatch(strNumber) &&
            objNaturalPattern.IsMatch(strNumber);
        }

        public static string GetRefNumber(string strExceptType, string PostedDate, string ID)
        {
            String _result = "";
            String _refnumber = "";
            MyDatabase _db = new MyDatabase();
            String _strSql = "SELECT CONVERT(VARCHAR,(CONVERT(DATETIME,'" + PostedDate + "',103)),112)";
            _result = _db.ExecuteScalarSqlStatement(_strSql).ToString();
            _refnumber = strExceptType + _result + ID;
            return _refnumber;
        }

        public static string GetRefNumber(Int64 FirstId)
        {
            string _vallasttwo = "";
            string _valfirstchar = "";
            string _valsecondchar = "";
            string _valremaining = "";
            string _result = "";
            Int64 _firstId = FirstId;
            if (_firstId.ToString().Length >= 2)
            {
                _valremaining = _firstId.ToString().Substring(0, _firstId.ToString().Length - 2);
                _vallasttwo = _firstId.ToString().Substring(_firstId.ToString().Length - 2, 2);
                _valfirstchar = _vallasttwo.Substring(0, 1);
                _valsecondchar = _vallasttwo.Substring(1, 1);
                _valfirstchar = NumberToChar(Convert.ToInt32(_valfirstchar));
                _valsecondchar = NumberToChar(Convert.ToInt32(_valsecondchar));
                _result = _valremaining + "" + _valfirstchar + "" + _valsecondchar;
            }
            else if (_firstId.ToString().Length == 1)
            {
                _valfirstchar = _firstId.ToString();
                _valfirstchar = NumberToChar(Convert.ToInt32(_valfirstchar));
                _result = _valfirstchar;
            }
          
            return _result;
        }

        public static string NumberToChar(int id)
        {
            string C = "";
            if (id == 1)
                C = "A";
            else if (id == 2)
                C = "B";
            else if (id == 3)
                C = "C";
            else if (id == 4)
                C = "D";
            else if (id == 5)
                C = "E";
            else if (id == 6)
                C = "F";
            else if (id == 7)
                C = "G";
            else if (id == 8)
                C = "H";
            else if (id == 9)
                C = "I";
            else if (id == 0)
                C = "J";
            return C;
        }

        public static string GetCarId(string QuoteNo)
        {
            string _val = "";
            string _result = "0";
            string str = QuoteNo;
            char[] letters = str.ToCharArray();
            for (int i = 3; i < letters.Length; i++)
            {
                _val += StringToNumber(letters[i].ToString());
            }
            if (_val.Length > 0 && IsInteger(_val) == true)
            {
                _result = _val;
            }
            return _result;
        }

        public static string StringToNumber(string No)
        {
            string C = "";
            if (No.ToUpper() == "A")
                C = "1";
            else if (No.ToUpper() == "B")
                C = "2";
            else if (No.ToUpper() == "C")
                C = "3";
            else if (No.ToUpper() == "D")
                C = "4";
            else if (No.ToUpper() == "E")
                C = "5";
            else if (No.ToUpper() == "F")
                C = "6";
            else if (No.ToUpper() == "G")
                C = "7";
            else if (No.ToUpper() == "H")
                C = "8";
            else if (No.ToUpper() == "I")
                C = "9";
            else if (No.ToUpper() == "J")
                C = "0";
            else
                C = No;
            return C;
        }

        public static void ClearAllSession(System.Web.UI.Page PageSession, string strExceptType)
        {
            #region Comment
            //string strUserId = string.Empty;
            //string strUserTypeId = string.Empty;
            //string strUserEmail = string.Empty;
            //string strUserPhoneNo = string.Empty;
            //string strUserName = string.Empty;

            //if (PageSession.Session[UserId] != null) strUserId = PageSession.Session[UserId].ToString();
            //if (PageSession.Session[UserTypeId] != null) strUserId = PageSession.Session[UserTypeId].ToString();
            //if (PageSession.Session[UserEmail] != null) strUserId = PageSession.Session[UserEmail].ToString();
            //if (PageSession.Session[UserPhoneNo] != null) strUserId = PageSession.Session[UserPhoneNo].ToString();
            //if (PageSession.Session[UserName] != null) strUserId = PageSession.Session[UserName].ToString();

            //PageSession.Session.Clear();
            //PageSession.Session.Abandon();

            //PageSession.Session[UserId] = strUserId;
            //PageSession.Session[UserTypeId] = strUserTypeId;
            //PageSession.Session[UserEmail] = strUserEmail;
            //PageSession.Session[UserPhoneNo] = strUserPhoneNo;
            //PageSession.Session[UserName] = strUserName;

            //PageSession.Session["UserId"] = "UserId";
            //PageSession.Session["UserTypeId"] = "UserTypeId";
            //PageSession.Session["UserEmail"] = "UserEmail";
            //PageSession.Session["UserPhoneNo"] = "UserPhone";
            //PageSession.Session["UserName"] = "UserName";
            //PageSession.Session["UserICNumber"] = "UserICNumber";
            //PageSession.Session["RequestUrl"] = "RequestUrl";
            //PageSession.Session["StartTime"] = "StartTime";
            //PageSession.Session["Guest"] = "Guest";
            //PageSession.Session["LoginHistoryId"] = "LoginHistoryId";
            //Car Insurance Session
            #endregion

            PageSession.Session["salt"] = null;
            PageSession.Session["ImageCount"] = null;

            if (strExceptType != "CI")
            {
                PageSession.Session["CarId"] = null;
                PageSession.Session["CarPolicyId"] = null;
                PageSession.Session["CarResultId"] = null;
                PageSession.Session["CarMoreDetailId"] = null;
                PageSession.Session["CarClaimHistoryId"] = null;
                PageSession.Session["CvvId"] = null;
            }

            //Home Loan
            if (strExceptType != "HF")
            {
                PageSession.Session["HFId"] = null;
                PageSession.Session["HFPersonnelId"] = null;
                PageSession.Session["HFResultId"] = null;
                PageSession.Session["HFPropertyId"] = null;
                PageSession.Session["HFUserName"] = null;
                PageSession.Session["HFPhoneNo"] = null;
                PageSession.Session["HFEmail"] = null;
            }

            //Personal Loan
            if (strExceptType != "PL")
            {
                PageSession.Session["PLId"] = null;
                PageSession.Session["PLUserName"] = null;
                PageSession.Session["PLPhoneNo"] = null;
                PageSession.Session["PLEmail"] = null;
                PageSession.Session["PLPersonnelId"] = null;
                PageSession.Session["PLResultId"] = null;
            }

            //Personal Accident
            if (strExceptType != "PA")
            {
                PageSession.Session["PAId"] = null;
                PageSession.Session["PAUserName"] = null;
                PageSession.Session["PAPhoneNo"] = null;
                PageSession.Session["PAEmail"] = null;
                PageSession.Session["PAPersonnelId"] = null;
                PageSession.Session["PAResultId"] = null;
                PageSession.Session["PAProposalId"] = null;
            }

            //Travel Insurance
            if (strExceptType != "TA")
            {
                PageSession.Session["TAId"] = null;
                PageSession.Session["TAUserName"] = null;
                PageSession.Session["TAPhoneNo"] = null;
                PageSession.Session["TAEmail"] = null;
                PageSession.Session["TAPersonnelId"] = null;
                PageSession.Session["TAResultId"] = null;
                PageSession.Session["TACustomerAge"] = null;
            }

            //Provider Session
            //if (strExceptType != "PV")
            //{
            //    PageSession.Session["ProviderCompanyId"] = null;
            //}

            //if (strExceptType != "GT")
            //{
            //    PageSession.Session["Guest"] = null;
            //}
            //CreditCard Compare Request
            if (strExceptType != "CC")
            {
                PageSession.Session["CCARId"] = null;
                PageSession.Session["CCRequestStatus"] = null;
                PageSession.Session["CCId"] = null;
                PageSession.Session["CCRFullName"] = null;
                PageSession.Session["CCRMobileNo"] = null;
                PageSession.Session["CCREmail"] = null;
                PageSession.Session["CCPersonnelId"] = null;
            }

            if (strExceptType == "LOGOUT")
            {
                ClearUserLoginCached(PageSession);
                PageSession.Session["UserId"] = null;
                PageSession.Session["UserRole"] = null;
                PageSession.Session["UserTypeId"] = null;
                PageSession.Session["UserEmail"] = null;
                PageSession.Session["UserPhoneNo"] = null;
                PageSession.Session["UserName"] = null;

                PageSession.Session["UserICNumber"] = null;
                PageSession.Session["RequestUrl"] = null;
                PageSession.Session["StartTime"] = null;
                //PageSession.Session["Guest"] = null;
                PageSession.Session["LoginHistoryId"] = null;
                PageSession.Session["LastLoginTime"] = null;
                PageSession.Session["ProviderCompanyId"] = null;
                PageSession.Session["IsProfileContactComplete"] = null;
                
            }
        }

        public static void CreateUpdateUserLoginCached(System.Web.UI.Page thisPage)
        {
            string sKey = CE.Configuration.MyConfigurationManager.GetAppSettingValue("UserCacheName");
            sKey += Convert.ToString(thisPage.Session[UserId].ToString());
            // Accessing the Cache Item extends the Sliding Expiration automatically
            if (thisPage.Cache[sKey] != null)
            {
                string sUser = thisPage.Cache[sKey].ToString();
            }
            else
            {
                TimeSpan SessTimeOut = new TimeSpan(0, 0, thisPage.Session.Timeout, 0, 0);
                thisPage.Cache.Insert(sKey, thisPage.Session[UserId].ToString(), null, DateTime.MaxValue, SessTimeOut,
                   System.Web.Caching.CacheItemPriority.NotRemovable, null);
            }
        }

        public static bool ClearUserLoginCached(System.Web.UI.Page thisPage)
        {
            bool _retValue = false;
            string sKey = CE.Configuration.MyConfigurationManager.GetAppSettingValue("UserCacheName");
            sKey += thisPage.Session[UserId].ToString();

            if (thisPage.Cache[sKey] == null)
            {
                _retValue = true;
            }
            else
            {
                thisPage.Cache.Remove(sKey);
                _retValue = true;
            }

            return _retValue;
        }

        public static Int64 GetPageAccess(Int64 UserId, string PageCode)
        {
            Int64 _result = 0;
            MyDatabase _db = new MyDatabase();
            string _spName = "sprocCXTHUserAccessReportsPagesSelectItem";

            SortedList _spara = new SortedList();
            _spara.Add("@UserId", UserId);
            _spara.Add("@PageCode", PageCode);
            _result = _db.ExecuteSP(_spName, _spara);

            return _result;
        }

        public static String SetCulture()
        {
            String selectedCulture = string.Empty;
            if (HttpContext.Current.Session["Language"] != null)
            {
                selectedCulture = HttpContext.Current.Session["Language"].ToString();
            }
            else
            {
                //selectedCulture = "th-TH";
                selectedCulture = ((System.Web.Configuration.GlobalizationSection)(System.Configuration.ConfigurationSettings.GetConfig("system.web/globalization"))).UICulture;
                HttpContext.Current.Session["Language"] = selectedCulture;
            }

            //UICulture = selectedCulture;
            //Culture = selectedCulture;

            //Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(selectedCulture);
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(selectedCulture);

            return selectedCulture;
        }

        public static String GetReferenceNumber(string Number, string ProviderId, string InsType)
        {
            string convertno = CE.Global.General.GetRefNumber(Convert.ToInt64(Number.ToString()));
            string _RefNo = "";
            if (ProviderId == "11")
            {
                _RefNo = "AZC" + convertno.ToString();
            }
            else if (ProviderId == "12")
            {
                _RefNo = "MSI" + convertno.ToString();
            }
            else if (ProviderId == "16")
            {
                _RefNo = "AXA" + convertno.ToString();
            }
            else if (ProviderId == "29")
            {
                _RefNo = "LMG" + convertno.ToString();
            }
            else if (ProviderId == "31")
            {
                _RefNo = "CTS" + convertno.ToString();
            }
            else if (ProviderId == "32")
            {
                _RefNo = "BKI" + convertno.ToString();
            }
            else if (ProviderId == "33")
            {
                _RefNo = "MTI" + convertno.ToString();
            }
            else if (ProviderId == "35")
            {
                _RefNo = "KPI" + convertno.ToString();
            }
            else if (ProviderId == "39")
            {
                _RefNo = "MIR" + convertno.ToString();
            }
            else if (ProviderId == "41")
            {
                _RefNo = "KUR" + convertno.ToString();
            }
            else if (ProviderId == "43")
            {
                _RefNo = "SMK" + convertno.ToString();
            }
            else if (ProviderId == "45")
            {
                _RefNo = "VRY" + convertno.ToString();
            }
            else if (ProviderId == "46")
            {
                _RefNo = "TMS" + convertno.ToString();
            }
            else if (ProviderId == "58")
            {
                _RefNo = "TVV" + convertno.ToString();
            }
            return _RefNo;
        }

        public static String GetProviderName(string ProviderId)
        {
            string _ProviderName = "All";
            if (ProviderId == "11")
            {
                _ProviderName = "Allianz CP";
            }
            else if (ProviderId == "12")
            {
                _ProviderName = "MSIG";
            }
            else if (ProviderId == "16")
            {
                _ProviderName = "AXA";
            }
            else if (ProviderId == "29")
            {
                _ProviderName = "LMG";
            }
            else if (ProviderId == "31")
            {
                _ProviderName = "Chartis";
            }
            else if (ProviderId == "32")
            {
                _ProviderName = "BKI";
            }
            else if (ProviderId == "33")
            {
                _ProviderName = "MuangThai";
            }
            else if (ProviderId == "35")
            {
                _ProviderName = "KrungThai";
            }
            else if (ProviderId == "39")
            {
                _ProviderName = "Mittare";
            }
            else if (ProviderId == "41")
            {
                _ProviderName = "Kurnia";
            }
            else if (ProviderId == "43")
            {
                _ProviderName = "Syn Mun Kong";
            }
            else if (ProviderId == "45")
            {
                _ProviderName = "Viriyah";
            }
            else if (ProviderId == "46")
            {
                _ProviderName = "Tokio Marine";
            }
            else if (ProviderId == "58")
            {
                _ProviderName = "Thaivivat";
            }
            return _ProviderName;
        }

        public static DateTime GetUTCDateTime()
        {
            DateTime _CurrentDateTime = DateTime.UtcNow.AddHours(7);
            return _CurrentDateTime;
        }
    }

    public enum CEUserType
    {
        SiteAdmin = 100,
        SiteUser = 200,
        Provider = 300,
        Customer = 400,
        Advertiser = 500,
        Guest = 600,
        Management = 700
    }
}
